package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.IdRes;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.spainterface.NmSwipeCardUtils;
import com.ly.hotel.spainterface.OnSwipeCardInterface;
import com.ly.hotel.util.IdChangeUtil;
import com.ly.hotel.util.InterfaceConfUtil;
import com.ly.hotel.util.ToastUtil;
import com.ly.hotel.webagent.UdpCallback;
import com.ly.hotel.webagent.UdpClient;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.ByteArrayInputStream;
import java.util.Timer;
import java.util.TimerTask;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;


/**
 * Created by SHUBEN on 2018/3/26.
 */

public class TipEvalDialog extends Dialog {

    private boolean haveEval = true;
    private boolean haveTip = false;
    private String artNo;
    private LinearLayout evalLayout;
    private LinearLayout tipLayout;
    private RadioGroup evalGroup;
    private TextView evalText;
    private EditText tipEdit;
    private Button btZero;
    private Button btOne;
    private Button btTwo;
    private Button btThree;
    private Button btFour;
    private Button btFive;
    private Button btSix;
    private Button btSeven;
    private Button btEight;
    private Button btNine;
    private Button btCls;
    private GridLayout keyGrid;
    private TextView artNoView;
    private ImageView swipImg;
    private TextView title;
    private Animation alphaAnimation;
    private Context mcontext;
    private NmSwipeCardUtils swipUtils;
    private Handler handler;
    private Timer mOffTime;
    private TimerTask tt;
    private int countTime;
    private TextView evalRes;
    private TextView tipRes;
    private TextView closeText;
    private String defaultTip = "30";
    private RadioButton evalGood;
    private String evalType;
    private static final int GET_KEYNO = 0;
    private static final int REQ_EVAL = 1;
    private static final int REQ_TIP = 2;
    private static final int CLOSE_DIALOG = 99;
    private boolean isSubmitedEval = true;
    private boolean isSubmitedTip = true;

    public TipEvalDialog(Context context, int theme) {
        super(context, theme);
        mcontext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_tip_eval);
        alphaAnimation = AnimationUtils.loadAnimation(mcontext, R.anim.alpha_anim);
        mOffTime = new Timer(true);
        evalLayout = findViewById(R.id.eval_layout);
        tipLayout = findViewById(R.id.tip_layout);
        evalGroup = findViewById(R.id.eval_group);
        evalText = findViewById(R.id.eval_Text);
        tipEdit = findViewById(R.id.tip_edit);
        btZero = findViewById(R.id.tip_btn_0);
        btOne = findViewById(R.id.tip_btn_1);
        btTwo = findViewById(R.id.tip_btn_2);
        btThree = findViewById(R.id.tip_btn_3);
        btFour = findViewById(R.id.tip_btn_4);
        btFive = findViewById(R.id.tip_btn_5);
        btSix = findViewById(R.id.tip_btn_6);
        btSeven = findViewById(R.id.tip_btn_7);
        btEight = findViewById(R.id.tip_btn_8);
        btNine = findViewById(R.id.tip_btn_9);
        btCls = findViewById(R.id.tip_btn_cls);
        title = findViewById(R.id.eval_title);
        swipImg = findViewById(R.id.eval_swipe);
        closeText = findViewById(R.id.eval_suc_close);
        evalGood = findViewById(R.id.eval_good);
        artNoView = findViewById(R.id.eval_artNo);
        keyGrid = findViewById(R.id.tip_input_grid);
        evalRes = findViewById(R.id.eval_res_text);
        tipRes = findViewById(R.id.tip_res_text);

        btCls.setOnClickListener(btnClick);
        btZero.setOnClickListener(btnClick);
        btOne.setOnClickListener(btnClick);
        btTwo.setOnClickListener(btnClick);
        btThree.setOnClickListener(btnClick);
        btFour.setOnClickListener(btnClick);
        btFive.setOnClickListener(btnClick);
        btSix.setOnClickListener(btnClick);
        btSeven.setOnClickListener(btnClick);
        btEight.setOnClickListener(btnClick);
        btNine.setOnClickListener(btnClick);

        handler = new Handler(){
            public void handleMessage(Message msg){
                switch (msg.what){
                    case GET_KEYNO:
                        parseResData(msg.what,msg.obj.toString());
                        break;
                    case REQ_EVAL:
                        parseResData(msg.what,msg.obj.toString());
                        break;
                    case REQ_TIP:
                        parseResData(msg.what,msg.obj.toString());
                        break;
                    case CLOSE_DIALOG:
                        if(countTime > 0){
                            closeText.setText(countTime + " 秒后关闭");
                        }else{
                            dismiss();
                        }
                        break;
                }
            }
        };

        swipUtils =  new NmSwipeCardUtils(new OnSwipeCardInterface() {
            @Override
            public void swipeCardListener(String cardId) {
                String newId = cardId.replaceAll("\r\n", "");
                if(newId.length() == 10) {
                    try {
                        long b = Long.parseLong(newId);
                        evalGroup.setVisibility(View.GONE);
                        keyGrid.setVisibility(View.GONE);
                        evalText.setVisibility(View.VISIBLE);
                        swipImg.clearAnimation();
                        swipImg.setVisibility(View.GONE);
                        title.setText("Loading...");
                        toGetEvalReq(newId,GET_KEYNO);
                    } catch (NumberFormatException e) {
                        Log.e("swipe", "刷卡含有非法字符，重刷！");
                        swipUtils.initSwipe();
                    }
                }else{
                    Log.e("swipe", "刷卡不足10位，重刷！");
                    swipUtils.initSwipe();
                }
            }
        });

        evalGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                RadioButton radbtn =  findViewById(checkedId);
                evalText.setText(radbtn.getText());
                switch (checkedId){
                    case R.id.eval_good:
                        evalType = "好评";
                        break;
                    case R.id.eval_middle:
                        evalType = "中评";
                        break;
                    case R.id.eval_bad:
                        evalType = "差评";
                        break;
                }
            }
        });


        Button backBtn = (Button) findViewById(R.id.dialog_back);
        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dismiss();
            }
        });
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.tip_btn_0:
                    if(!TextUtils.isEmpty(tipEdit.getText().toString())){
                        setEditText("0");
                    }
                    break;
                case R.id.tip_btn_1:
                    setEditText("1");
                    break;
                case R.id.tip_btn_2:
                    setEditText("2");
                    break;
                case R.id.tip_btn_3:
                    setEditText("3");
                    break;
                case R.id.tip_btn_4:
                    setEditText("4");
                    break;
                case R.id.tip_btn_5:
                    setEditText("5");
                    break;
                case R.id.tip_btn_6:
                    setEditText("6");
                    break;
                case R.id.tip_btn_7:
                    setEditText("7");
                    break;
                case R.id.tip_btn_8:
                    setEditText("8");
                    break;
                case R.id.tip_btn_9:
                    setEditText("9");
                    break;
                case R.id.tip_btn_cls:
                    tipEdit.setText("");
                    defaultTip = "30";
                    break;
            }
        }
    };

    private void setEditText(String num){
        String nowText = tipEdit.getText().toString();
        if(nowText.length() < 8) {
            tipEdit.setText(nowText + num);
            defaultTip = tipEdit.getText().toString();
        }else{
            ToastUtil.showShortToast(mcontext,"输入限制",1500);
        }
    }

    //初始化数据
    public void setData(boolean haveEval,boolean haveTip,String artNo){
        countTime = 7;
        this.haveEval = haveEval;
        isSubmitedEval = !haveEval;
        this.haveTip = haveTip;
        isSubmitedTip = !haveTip;
        this.artNo = artNo;
        artNoView.setText(artNo);
        if(!haveEval){
            evalLayout.setVisibility(View.GONE);
        }
        if(!haveTip){
            tipLayout.setVisibility(View.GONE);
        }
        swipUtils.initSwipe();
        swipImg.startAnimation(alphaAnimation);
        evalGood.setChecked(true);
    }

    //分析接口提交评价或小费
    private void toGetEvalReq(final String id,final int type){
        if(MyApplication.interfaceVersion.contains("JXD")){
            final String interfaceIp = InterfaceConfUtil.getConf("me","ip","172.16.1.205");
            final String interfacePort = InterfaceConfUtil.getConf("me","port","8081");
            final String cardConf = InterfaceConfUtil.getConf("me","cardtype","ID_10");
            new Thread(){
                @Override
                public void run() {
                    super.run();
                    final Message msg = new Message();
                    msg.what = type;
                    String request = "";
                    switch (type) {
                        case GET_KEYNO:
                            String cardId = IdChangeUtil.getId(id,cardConf);
                            request = "<gs ver=\"1.0\" function=\"桑拿卡号转匙牌号\" mode = \"request\"><ArtFlag>0" +
                                    "</ArtFlag><RfCardno>" + cardId + "</RfCardno></gs>";
                            break;
                        case REQ_EVAL:
                            request = "<gs ver=\"1.0\" function=\"桑拿客人评价\" mode = \"request\"><KeyNo>" + id +
                                    "</KeyNo><ArtNo>" + artNo + "</ArtNo><Performance>" + evalType + "</Performance></gs>";
                            break;
                        case REQ_TIP:
                            request = "<gs ver=\"1.0\" function=\"桑拿小费录入\" mode = \"request\"><RoomNo>" + MyApplication.getDeviceInfo().getName() +
                                    "</RoomNo><KeyNo>" + id + "</KeyNo><ArtNo>" + artNo + "</ArtNo>" +
                                    "<Amount>" + defaultTip + "</Amount></gs>";
                            break;
                        default:
                            break;
                    }
                    Log.d("udp", interfaceIp + "," + interfacePort + "," + request );
                    UdpCallback c = new UdpCallback() {
                        @Override
                        public void receive(String s) {
                            s =  s.replace("\r\n", "").replace("'", "’");
                            msg.obj = s;
                            handler.sendMessage(msg);
                        }
                    };
                    try {
                        int p = Integer.parseInt(interfacePort);
                        new UdpClient(interfaceIp, p, c, "<gs", "</gs>", "Msg").send(request);
                    } catch (NumberFormatException n) {
                        msg.obj = "";
                        handler.sendMessage(msg);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        msg.obj = "";
                        handler.sendMessage(msg);
                    }
                }
            }.start();
        }
    }

    //解析接口服务器数据
    private void parseResData(int type, String parseStr) {
        if(!TextUtils.isEmpty(parseStr)) {
            try {
                if (!parseStr.startsWith("Msg")) {
                    DocumentBuilderFactory domfac = DocumentBuilderFactory.newInstance();
                    DocumentBuilder dombuilder = domfac.newDocumentBuilder();
                    Document doc = dombuilder.parse(new ByteArrayInputStream(parseStr.getBytes("utf-8")));
                    NodeList obj = doc.getElementsByTagName("gs");
                    switch (type) {
                        case GET_KEYNO:
                            NodeList keyList = ((Element) obj.item(0)).getElementsByTagName("keyno");
                            String keyno = "";
                            if (keyList.getLength() >= 1 && keyList.item(0) != null && keyList.item(0).hasChildNodes()) {
                                keyno = keyList.item(0).getFirstChild().getNodeValue();
                            }
                            if(!TextUtils.isEmpty(keyno)){
                                if(haveEval){
                                    toGetEvalReq(keyno,REQ_EVAL);
                                }
                                if(haveTip){
                                    toGetEvalReq(keyno,REQ_TIP);
                                }
                            }else{
                                setResText(false,type,"提交失败！请手工录入！");
                            }
                            break;
                        case REQ_EVAL:
                            NodeList rcList = ((Element) obj.item(0)).getElementsByTagName("rc");
                            NodeList errList = ((Element) obj.item(0)).getElementsByTagName("errmsg");
                            String rc = "";
                            String errmsg = "";
                            if (rcList.getLength() >= 1 && rcList.item(0) != null && rcList.item(0).hasChildNodes()) {
                                rc = rcList.item(0).getFirstChild().getNodeValue();
                            }

                            if (errList.getLength() >= 1 && errList.item(0) != null && errList.item(0).hasChildNodes()) {
                                errmsg = errList.item(0).getFirstChild().getNodeValue();
                            }
                            if(rc.equals("0")){
                                isSubmitedEval = true;
                                setResText(true,type,"提交成功！");
                            }else{
                                setResText(false,type,"提交失败！" + errmsg + "请手工录入！");
                            }
                            break;
                        case REQ_TIP:
                            NodeList rcList1 = ((Element) obj.item(0)).getElementsByTagName("rc");
                            NodeList errList1 = ((Element) obj.item(0)).getElementsByTagName("errmsg");
                            String rc1 = "";
                            String errmsg1 = "";
                            if (rcList1.getLength() >= 1 && rcList1.item(0) != null && rcList1.item(0).hasChildNodes()) {
                                rc1 = rcList1.item(0).getFirstChild().getNodeValue();
                            }

                            if (errList1.getLength() >= 1 && errList1.item(0) != null && errList1.item(0).hasChildNodes()) {
                                errmsg1 = errList1.item(0).getFirstChild().getNodeValue();
                            }
                            if(rc1.equals("0")){
                                isSubmitedTip = true;
                                setResText(true,type,"提交成功！");
                            }else{
                                setResText(false,type,"提交失败！" + errmsg1 + "请手工录入！");
                            }
                            break;
                    }
                }else {
                    String errmsg = "请手工录入！";
                    setResText(false,type,"提交失败！" + parseStr + errmsg);
                }
            } catch (Exception e) {
                setResText(false,type,"数据解析出错！请联系技术人员");
            }
        }else {
            setResText(false,type,"提交失败！请手工录入！");
        }
    }

    private void setResText(boolean isSuc,int type,String msg){
        title.setText("");
        if(type == GET_KEYNO){
            if(haveTip) {
                if (isSuc) {
                    tipRes.setTextColor(mcontext.getResources().getColor(R.color.green));
                } else{
                    tipRes.setTextColor(mcontext.getResources().getColor(R.color.red));
                }
                tipRes.setText("小费" + msg);
                tipRes.setVisibility(View.VISIBLE);
            }
            if(haveEval){
                if (isSuc) {
                    evalRes.setTextColor(mcontext.getResources().getColor(R.color.green));
                } else{
                    evalRes.setTextColor(mcontext.getResources().getColor(R.color.red));
                }
                evalRes.setText("评价" + msg);
                evalRes.setVisibility(View.VISIBLE);
            }
        } else if(type == REQ_EVAL){
            if (isSuc) {
                evalRes.setTextColor(mcontext.getResources().getColor(R.color.green));
            } else{
                evalRes.setTextColor(mcontext.getResources().getColor(R.color.red));
            }
            evalRes.setText("评价" + msg);
            evalRes.setVisibility(View.VISIBLE);
        } else if(type == REQ_TIP){
            if (isSuc) {
                tipRes.setTextColor(mcontext.getResources().getColor(R.color.green));
            } else{
                tipRes.setTextColor(mcontext.getResources().getColor(R.color.red));
            }
            tipRes.setText("小费" + msg);
            tipRes.setVisibility(View.VISIBLE);
        }
        if(isSubmitedEval && isSubmitedTip){
            showCloseText();
        }
    }

    @Override
    protected void onStop() {
        if(tt != null){
            tt.cancel();
        }
        swipUtils.setOnSwipeFlag(false);
        super.onStop();
    }


    private void showCloseText(){
        closeText.setVisibility(View.VISIBLE);
        tt = new TimerTask() {
            public void run() {
                if (countTime > 0) {
                    countTime--;
                }
                Message msg = new Message();
                msg.what = CLOSE_DIALOG;
                handler.sendMessage(msg);
            }
        };
        mOffTime.schedule(tt, 0, 1000);
    }
}